<?php
namespace app\api\controller;

use tool\Res;

class User extends Base
{
    public function waplogin()
    {
        $app=$this->getwxapp();
        $wx_user_object = $app->oauth->user();
        $wx_user=$wx_user_object->original;
        if(empty($wx_user)){
            abort(404,"登录失败");
        }
        $from=i("from");

        $openid=$wx_user['openid'];
        $user=model("user")->where("openid",$openid)->find();
        if(empty($user)){
            model("user")->insert(['openid'=>$openid,"reg_time"=>now()]);
            $user=model("user")->where("openid",$openid)->find();
        }
        $user_id=$user['id'];
        model("user")->where("id",$user_id)->update([
            "nickname"=>$wx_user['nickname'],
            "sex"=>$wx_user['sex'],
            "city"=>$wx_user['city'],
            "province"=>$wx_user['province'],
            "country"=>$wx_user['country'],
            "avatar_before"=>str_replace("/132","/0",$wx_user['headimgurl']),
        ]);

        doRequest("https://server.xckj789.com/api/user/setavatar",["user_id"=>$user_id]);
        $token=cache("user_id_bytoken_{$user['id']}");
        if(empty($token )){
            $token=uniqid();

        }
        cache("user_id_bytoken_{$user['id']}",$token,86400*7);
        cache("user_id_$token",$user['id'],86400*7);
        cookie("user_token",$token,["domain"=>"xckj789.com"]);
        $this->redirect($from);

    }


    public function setavatar(){
        $user_id=i("user_id");
        $user=model("user")->where("id",$user_id)->find();
        $avatar=Res::upload("avatar",$user['avatar_before'],"jpg");
        model("user")->where("id",$user_id)->update(['avatar'=>$avatar]);
    }

    public function get(){
        $user=$this->getuser(false);
        $group_code=i("group_code")??null;
        $this->bindgroup($user['id'],$group_code);
        $user['money']=money($user['id']);
        $group=model("group")->where("user_id",$user['id'])->find();
        $user['isgroup']=empty($group)?false:true;
        return s($user);
    }


}
